import json

import requests
from   common.recordlog import logs
from  requests import utils
from   common.read_yaml import   Read_yamlData
import   pytest
class Send(object):
    def __init__(self):
        self.read=Read_yamlData()

    # def get(self, header, url, data):
    #     if header is None:
    #         res = requests.get(params=data, url=url)
    #     else:
    #         res = requests.get(headers=header, params=data, url=url)
    #
    #     return res.json()
    #
    #
    # def post(self, data, url, header):
    #     if header is None:
    #         res = requests.post(data=data, url=url, verify=False)
    #     else:
    #         res = requests.post(data=data, url=url, headers=header)
    #     return res.json()

    def  send_request(self,**kwargs):
        cookie={}
        session=requests.session()
        try:
            result=session.request(**kwargs)
            set_cookie=requests.utils.dict_from_cookiejar(result.cookies)
            if  set_cookie:
                cookie['Cookie']=set_cookie
                self.read.write_yaml_data(set_cookie)
                logs.info(f'cookies:{set_cookie}')
            logs.info(f'接口的实际返回信息{result.text if  result.text  else  result}')
        except  requests.exceptions.ConnectionError:
            logs.error('接口连接服务器异常！')
            pytest.fail('接口请求异常，可能是request的连接次数过多或者请求速度过快导致程序报错')
        except  requests.exceptions.HTTPError:
            logs.error('http异常')
            pytest.fail('http请求异常')
        except  requests.exceptions.RequestException as  e:
            logs.error(e)
            pytest.fail('请求异常,请检查系统或数据是否正常')
        return   result



    def  run_main(self,name,url,case_name,header,method,cookies=None,file=None,**kwargs):
        try:
            logs.info(f'接口名称:{name}')
            logs.info(f'接口请求地址:{url}')
            logs.info(f'请求方法:{method}')
            logs.info(f'测试用例名称:{case_name}')
            logs.info(f'请求头:{header}')
            logs.info(f'Cookies:{cookies}')
            req_params=json.dumps(kwargs,ensure_ascii=False)
            if  'data'  in  kwargs.keys():
                logs.info(f'请求参数:{kwargs}')
            elif 'json'  in  kwargs.keys():
                logs.info(f'请求参数:{kwargs}')
            elif  'params'  in  kwargs.keys():
                logs.info(f'请求参数:{kwargs}')
        except Exception  as  e:
            logs.error(e)
        response=self.send_request(method=method,url=url,headers=header,cookies=cookies,verify=False,**kwargs)
        return  response






if __name__ == '__main__':
    url = 'http://127.0.0.1:8787/dar/user/login'
    header = {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}
    data = {"user_name": "test01",
            "passwd": "admin123"}
    send = Send()
    res = send.run_main(header=header, url=url, data=data,method='post',name='接口登录',case_name='用户和密码正确登录')
    print(res)
    print(type(res))
